package top.birdhk.TestAPI.tableapi;

import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import top.birdhk.TestAPI.beans.SensorReading;

public class TableTestExample {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        // 1.读取数据
        DataStreamSource<String> dataStream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");


        // 2.转换成POJO
        SingleOutputStreamOperator<SensorReading> inputStream = dataStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });


        // 3.创建表的环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);


        // 4.基于流创建一张表
        Table dataTable = tableEnv.fromDataStream(inputStream);


        // 5.调用table API进行转换操作
        Table resultTable = dataTable
                .select("id,temperature")
                .where("id = 's10'");


        // 6.如果想要使用SQL的方式，需要注册该表
        tableEnv.createTemporaryView("sensor",dataTable);
        String sql = "select id,temperature  from sensor where id = 's10'";
        Table sqlQuery = tableEnv.sqlQuery(sql);

        DataStream<Row> rowDataStream = tableEnv.toAppendStream(sqlQuery, Row.class);


        rowDataStream.print("tableAPI");


        env.execute();

    }



}
